package com.mk.security.distributed.uaa.dao;

import com.mk.security.distributed.uaa.model.PermissionDto;
import com.mk.security.distributed.uaa.model.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

//@Mapper
////@Repository
//public interface UserDao extends BaseMapper<UserDto> {
//    @Autowired
//    private JdbcTemplate jdbcTemplate;
//
//    public UserDto getUserByUsername(String username){
//        String sql="select * from t_user where username=?";
//        List<UserDto> users = jdbcTemplate.query(sql, new Object[]{username}, new BeanPropertyRowMapper<>(UserDto.class));
//        if(users!=null){
//            return users.get(0);
//        }
//        return null;
//    }
//
//}


@Repository
public class UserDao  {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public UserDto getUserByUsername(String username){
        String sql="select * from t_user where username=?";
        List<UserDto> users = jdbcTemplate.query(sql, new Object[]{username}, new BeanPropertyRowMapper<>(UserDto.class));
        if(users!=null){
            return users.get(0);
        }
        return null;
    }

    //根据用户id查询用户权限
    public List<String> findPermissionsByUserId(String userId){
        String sql="SELECT * from t_permission WHERE id in (SELECT permission_id FROM t_role_permission WHERE role_id in\n" +
                "(SELECT role_id from t_user_role WHERE user_id =?))";
        List<PermissionDto> list = jdbcTemplate.query(sql, new Object[]{userId}, new BeanPropertyRowMapper<>(PermissionDto.class));
        List<String> permission=new ArrayList<>();
//        list.stream().map((item)->{
//            permission.add(item.getCode());
//            return permission;
//        }).collect(Collectors.toList());
        list.forEach(item->
                    permission.add(item.getCode()));
        return permission;
    }
}
